<script setup lang="ts">
import { ref, onMounted } from 'vue';
const canvasRef = ref();
const url = ref(''); // 图片地址

onMounted(()=>{
  const ctx = canvasRef.value.getContext('2d');
  const img = new Image();
  img.src = "/src/assets/img/logo01.png";
  img.onload = function() { 
    ctx.drawImage(this, 20, 20); // 图片，x, y
    // ctx.drawImage(this, 20, 300, 40, 40); // 图片，x, y, w, h
    // ctx.drawImage(this, 50, 50, 100, 100, 300, 20, 300, 300 ); // 图片，sx, sy, sw, sh, tx, ty, tw, th
  }
});

const save = () => {
  // 将canvas数据转成base64数据
  const base64 = canvasRef.value.toDataURL("image/png");
  // console.log('=================', base64);
  url.value = base64;
  const img = base64.replace("image/png", "image/octet-stream"); // 将canvas转换为图片

  const link = document.createElement('a');  // 创建一个新的 a 元素
  link.href = img;
  link.download = 'download.png';  // 设置图片名
  link.click(); // 模拟点击事件，开始下载图片
}

</script>

<template>
  <canvas width="600" height="600" class="canvas" ref="canvasRef"></canvas>
  <button @click="save">保存为图片</button>
  <img :src="url">
</template>

<style scoped>
.canvas {
  width: 600px;
  height: 600px;
  border: 1px solid #d3d3d3;
  margin: 20px;
}
</style>